package m.server.web.req;

import m.system.RuntimeData;
import m.system.util.FileUtil;
import m.system.util.GenerateID;

import java.io.File;

public class FormData {
    private final String name;
    private final boolean isFile;
    private final String fileName;
    private final byte[] bytes;
    private File file;
    private FormData(boolean isFile,String name,byte[] bytes,String fileName){
        this.name=name;
        this.isFile=isFile;
        this.bytes=bytes;
        this.fileName=fileName;
    }
    public static FormData newString(String name,byte[] bytes){
        return new FormData(false,name,bytes,null);
    }
    public static FormData newFile(String name,byte[] bytes,String fileName){
        return new FormData(true,name,bytes,fileName);
    }
    public File getFile() {
        if(null==file){
            try {
                this.file= FileUtil.getFile(RuntimeData.getClassTmp()+ GenerateID.tempKey()+"/"+fileName);
                FileUtil.writeFile(file.getPath(), bytes);
                return file;
            } catch (Exception ignored) {}
        }
        return null;
    }
    public void destroy() {
        if(null!=file){
            file.delete();
            file.getParentFile().delete();
        }
    }
    public String getString(){
        if(isFile){
            return getFile().toString();
        }else{
            return new String(this.bytes);
        }
    }

    public String getFileName() {
        return fileName;
    }

    public String getName() {
        return name;
    }

    public boolean isFile() {
        return isFile;
    }

    public byte[] getBytes() {
        return bytes;
    }
}
